'use strict'
const fs = require('fs');
const inquirernpm = require('inquirer')
const Spinner = require('cli-spinner').Spinner

function spinner(msg, spinnerString = '|/-\\') {
    const spinner = new Spinner(`${msg}.. %s`)
    spinner.setSpinnerString(spinnerString)
    spinner.start()
    return spinner
}


function isObject(o) {
    return Object.prototype.toString.call(o) === '[object Object]';
}

function inquirer({choices, defaultValue, message, type = 'list', require = true, mask = '*'}) {
    const options = {
        type,
        name: 'name',
        message,
        default: defaultValue,
        require,
        mask,
    }
    if (type === 'list') {
        options.choices = choices;
    }
    return inquirernpm.prompt(options).then((answer) => answer.name)
}

// 兼容两个平台
function execCommand(command, args, options) {
    const win32 = process.platform === 'win32';
    const cmd = win32 ? 'cmd' : command;
    const cmdArgs = win32 ? ['/c'].concat(command, args) : args;
    return require('child_process').spawn(cmd, cmdArgs, options || {});
}

function spinnerStart(msg, spinnerString = '|/-\\') {
    const Spinner = require('cli-spinner').Spinner;
    const spinner = new Spinner(msg + ' %s');
    spinner.setSpinnerString(spinnerString);
    spinner.start();
    return spinner;
}

function sleep(timeout = 1000) {
    return new Promise(resolve => setTimeout(resolve, timeout));
}

function readFile(path, options = {}) {
    if (fs.existsSync(path)) {
        const buffer = fs.readFileSync(path);
        if (buffer) {
            if (options.toJson) {
                return buffer.toJSON();
            } else {
                return buffer.toString();
            }
        }
    } else {
        return null;
    }
}

function writeFile(path, data, {rewrite = true} = {}) {
    if (fs.existsSync(path)) {
        if (rewrite) {
            fs.writeFileSync(path, data);
            return true;
        } else {
            return false;
        }
    } else {
        fs.writeFileSync(path, data);
        return true;
    }
}

function terminalLink(key, url) {
    if (!url) {
        return require('terminal-link')(key, key);
    } else {
        return require('terminal-link')(key, url);
    }
}


module.exports = {
    terminalLink,
    isObject,
    execCommand,
    spinnerStart,
    sleep,
    readFile,
    writeFile,
    inquirer,
    spinner
};
